<template>
  <div class="mobile-question-purchase">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="题库购买"
    ></white-header>
    <div class="purchase-detail">
      <div class="purchase-detail-content">
        <div class="purchase-detail-left">
          <img
            class="purchase-detail-left-cover"
            :src="
              question_obj.cover || '/img/mobile/question_menus_subject.png'
            "
            alt=""
          />
        </div>
        <div class="purchase-detail-right">
          <p
            class="purchase-detail-name"
            :title="question_obj.questionGroupName"
          >
            {{ question_obj.questionGroupName }}
          </p>
          <p class="purchase-detail-coursename">
            {{ question_obj.courseName }}
          </p>
          <p class="purchase-detail-price">
            <span>￥{{ price }} / {{ year }}</span>
            <span class="old_price" v-if="isDiscount"
              >￥{{ question_obj.price }} / {{ year }}</span
            >
          </p>
        </div>
      </div>
      <div class="purchase-detail-pay_list">
        <van-radio-group v-model="payType">
          <div class="pay_item ye_pay border-bottom" @click="payType = 1">
            <div class="pay_item_left">
              <img src="/img/mobile/account_menus_balance.png" alt="" />
              余额
            </div>
            <van-radio :name="1" />
          </div>
          <div :class="['pay_item','wx_pay',!is_in_wechat ? 'border-bottom' : '']" @click="payType = 2">
            <div class="pay_item_left">
              <img src="/img/mobile/member_payment_wechat.png" alt="" />
              微信
            </div>
            <van-radio :name="2" />
          </div>
          <div
            class="pay_item zfb_pay"
            @click="payType = 3"
            v-show="!is_in_wechat"
          >
            <div class="pay_item_left">
              <img src="/img/mobile/member_payment_alipay.png" alt="" />
              支付宝
            </div>
            <van-radio :name="3" />
          </div>
        </van-radio-group>
      </div>
      <div v-if="appAliPayInfo" style="width:100%;overflow: auto;word-break: break-all;">
        {{appAliPayInfo}}
      </div>
      <div class="bottom-area">
        <div class="bottom-area-price">合计：<span>￥{{price}}</span></div>
        <div class="bottom-area-pay-btn" @click="handlePay">确认支付</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { getQuestionBankOne } from "~/api/v2-question-bank/question-bank";
import { buyQuestionBank } from "~/api/v2-question-bank/order.js";
import { baseUrl, socketUrl } from "~/config/conf";
import { wexinPay, wxJspay } from "~/utils/pay";
import {
  generateOrder,
  getCourseBuyToH5Alipay,
  getCourseBuyToH5Wx,
  getCourseBuyWxAuthorization,
  getCourseBuyWxBrowserPay,
  getCourseBuyWxAppPay,
  getCourseBuyAlipayAppPay
} from "~/api/order";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
export default {
  name: "question-purchase",
  components: {
    WhiteHeader
  },
  data() {
    return {
      question_obj: {},
      payType: 1,
      websock: null,
      timer: null, //节流计时器
      socketFailedCount: 0, //socket重连计数器
      orderNo: "",
      pay_success: false,
      isShowPayList: false,
      appAliPayInfo:''
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      major_list(state) {
        return state.major_list;
      },
      member_discount(state) {
        return state.member_discount;
      },
      user_member(state) {
        return state.member_info;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      }
    }),
    isWxAuthorization() {
      if (this.$route.query.isWxAuthorization) {
        return true;
      } else {
        return false;
      }
    },
    currentOrderNo() {
      return this.$route.query.orderNo || this.orderNo || "";
    },
    question_id() {
      return this.$route.query.qid;
    },
    price() {
      if (this.question_obj.isFree) {
        return 0.0;
      } else if (this.isDiscount) {
        return this.question_obj.discountPrice;
      } else {
        return this.question_obj.price;
      }
    },
    isDiscount() {
      if (this.question_obj.isDiscount == 1) {
        let current_time = new Date().getTime();
        let discount_start_time = new Date(
          this.question_obj.discountStartTime
        ).getTime();
        let discount_end_time = new Date(
          this.question_obj.discountEndTime
        ).getTime();
        return (
          discount_start_time <= current_time &&
          current_time < discount_end_time
        );
      } else {
        return false;
      }
    },
    year() {
      if (this.question_obj.effectiveTime) {
        return this.question_obj.effectiveTime + "年";
      } else {
        return "0年";
      }
      // if(this.question_obj.isLong == 1){
      //   return "长期";
      // }else{
      //   return this.question_obj.effectiveTime + "年";
      // }
    }
  },
  watch: {
    currentOrderNo:{
      handler:function(oldV,newV){
        if(this.$route.query.orderNo || this.orderNo){
          this.initWebSocket();
        }
      },
      immediate:true
    }
  },
  methods: {
    ...mapActions(["getMineV2QuestionBankList"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_QUESTION_LIST"
    ]),
    async wxBrowserPay(){
      if(this.isWxAuthorization){
        let WxBrowserPayResult = await getCourseBuyWxBrowserPay({orderNo:this.currentOrderNo});
          if (WxBrowserPayResult && WxBrowserPayResult.data && WxBrowserPayResult.data.code == 200) {
              const { data } = WxBrowserPayResult.data;
              console.log(
              "=====================微信JS支付====================="
              );
              wxJspay(
              data,
              res => {
                  console.log("微信JS支付结果：", res);
              },
              err => {
                  console.log(err);
              }
              );
          } else {
            this.$toast("调起失败");
          }
      }
    },
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "buyOrderInfo/" + this.currentOrderNo;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t134"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      try {
        const result = JSON.parse(e.data);
        if (result.code == 200) {
          let questionId = result.data.productId;
          // 付款成功
          this.pay_success = true;
          this.is_show_wechat_pay = false;
          this.paySuccess(questionId);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t128"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    retryConnectSocket() {
      this.debounce(async () => {
        this.socketFailedCount = this.socketFailedCount + 1;
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    },
    // 获取题库详情
    async getQueationDetail() {
      this.SET_IS_LOADING(true);
      let result = await getQuestionBankOne(this.question_id);
      console.log("获取当前题库：", result);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data) {
          this.question_obj = data;
        }
      }
      this.SET_IS_LOADING(false);
    },
    // 购买成功回调
    paySuccess(questionId) {
      let id = questionId || this.question_id;
      this.getMineV2QuestionBankList();
      this.$toast("购买成功");
      this.$router.replace("/m/v2-question-detail?id=" + id);
    },
    // 处理价格
    turnString(num) {
      var re = /^[0-9]+$/;
      var re2 = /^[0-9]+(\.[0-9]{1})$/;
      if (re.test(num)) {
        num += ".00";
      }
      if (re2.test(num)) {
        num += "0";
      }
      return num;
    },
    async handlePay() {
      let __price__ = Number(
        this.question_obj.isFree
          ? 0
          : this.isDiscount
          ? this.question_obj.discountPrice
          : this.question_obj.price
      ).toFixed(2);
      console.log(__price__);
      if (this.payType == 1) {
        console.log("余额支付");
        this.$dialog
          .confirm({
            title: this.$t("locale.mobile.order.t6"),
            message:
              this.$t("locale.mobile.order.t7") +
              __price__ +
              this.$t("locale.mobile.order.t8")
          })
          .then(async () => {
            if (__price__ > this.user_info.balance) {
              this.$dialog
                .confirm({
                  title: this.$t("locale.mobile.order.t9"),
                  message:
                    this.$t("locale.mobile.order.t10") +
                    (__price__ - this.user_info.balance).toFixed(2) +
                    this.$t("locale.mobile.order.t11"),
                  confirmButtonText: this.$t("locale.mobile.order.t12")
                })
                .then(() => {
                  this.$router.push({
                    path: "/m/wallet",
                    query: {
                      num: (__price__ - this.user_info.balance).toFixed(2),
                      rdurl: this.$route.fullPath
                    }
                  });
                });
            } else {
              let params = {
                questionGroupId: this.question_id,
                userId: this.user_info.id,
                price: this.turnString(__price__),
                ip: returnCitySN.cip
              };
              this.SET_IS_LOADING(true);
              let result = await buyQuestionBank(params);
              console.log("题库购买：", result);
              if (result && result.data && result.data.code == 200) {
                this.paySuccess();
              } else {
                if (result && result.data && result.data.code == 420) {
                  this.$toast("余额不足，购买失败!");
                } else if (
                  result &&
                  result.data &&
                  result.data.code == 1001
                ) {
                  this.$toast(result.data.msg);
                } else {
                  this.$toast("购买失败，请稍后重试！");
                }
              }
              this.SET_IS_LOADING(false);
            }
          })
          .catch(() => {});
      } else if (this.payType == 2) {
        if (!this.currentOrderNo) {
          let params = {
            questionGroupId: this.question_id,
            userId: this.user_info.id,
            price: this.turnString(__price__),
            ip: returnCitySN.cip,
            type: 4,
            payType: 2
          };
          let result = await generateOrder(params);
          if (result && result.data && result.data.code == 200) {
            const { orderNo } = result.data.data;
            this.orderNo = orderNo;
          } else if (result && result.data && result.data.code == 420) {
            this.$toast(this.$t("locale.mobile.order.t14"));
            return;
          } else if (result && result.data && result.data.code == 1001) {
            this.$toast("课程购买人数达到上限！");
            return;
          } else {
            this.$toast(this.$t("locale.mobile.order.t15"));
            return;
          }
        }
        if (this.is_in_wechat) {
          if (this.is_in_minigram) {
            wx.miniProgram.navigateTo({
              url: `/pages/buypay/index?orderNo=${this.currentOrderNo}`,
              success: function() {
                console.log("成功跳转小程序");
              },
              fail: function() {
                console.log("跳转小程序失败");
                this.$toast("小程序微信支付暂不可用");
              },
              complete: function() {
                console.log("完成");
              }
            });
            // this.$toast("小程序微信支付暂不可用");
          } else {
            // 进行微信授权--此处要修改-去掉授权
            if (this.isWxAuthorization) {
              let WxBrowserPayResult = await getCourseBuyWxBrowserPay({
                orderNo: this.currentOrderNo
              });
              if (
                WxBrowserPayResult &&
                WxBrowserPayResult.data &&
                WxBrowserPayResult.data.code == 200
              ) {
                const { data } = WxBrowserPayResult.data;
                console.log(
                  "=====================微信JS支付====================="
                );
                wxJspay(
                  data,
                  res => {
                    console.log("微信JS支付结果：", res);
                  },
                  err => {
                    console.log(err);
                  }
                );
              } else {
                this.$toast("调起失败");
              }
            } else {
              let WxAuthorizationResult = await getCourseBuyWxAuthorization({
                orderNo: this.currentOrderNo
              });
              if (
                WxAuthorizationResult &&
                WxAuthorizationResult.data &&
                WxAuthorizationResult.data.code == 200
              ) {
                window.location.href = WxAuthorizationResult.data.msg;
              } else {
                this.$toast(this.$t("locale.mobile.login.t19"));
              }
            }
          }
        } else {
          if (window.hasOwnProperty("flutter_inappwebview")) {
            // this.$toast("进来了")
            console.log(
              "=====================微信App支付====================="
            );
            let appPayresult = await getCourseBuyWxAppPay({
              orderNo: this.currentOrderNo
            });
            if (
              appPayresult &&
              appPayresult.data &&
              appPayresult.data.code == 200
            ) {
              // this.$toast("调起支付成功")
              const {
                appid,
                partnerid,
                noncestr,
                timestamp,
                sign,
                prepayid,
                amount
              } = appPayresult.data.data;
              // this.appAliPayInfo = JSON.stringify(appPayresult.data.data);
              let arg = JSON.stringify({
                type: "wxpay",
                data: {
                  appId: appid,
                  partnerId: partnerid,
                  prepayId: prepayid,
                  packageValue: appPayresult.data.data.package,
                  nonceStr: noncestr,
                  timeStamp: timestamp,
                  sign: sign,
                  amount: amount / 100
                }
              });
              // this.$toast(arg)
              window.flutter_inappwebview
                .callHandler("Pay", arg)
                .then(res => {
                  console.log("微信支付成功！");
                  console.log(res);
                })
                .catch(err => {
                  this.$toast("支付失败");
                });
            } else {
              this.$toast("支付失败" + result.data ? result.data.msg : null);
            }
          } else {
            console.log("=====================微信H5支付=====================");
            let H5WxResult = await getCourseBuyToH5Wx({
              orderNo: this.currentOrderNo
            });
            if (H5WxResult && H5WxResult.data && H5WxResult.data.code == 200) {
              const { data } = H5WxResult.data;
              let redirect_url =
                window.location.href +
                "&orderNo=" +
                this.currentOrderNo +
                "&isSuccess=1";
              window.location.href = `${
                data.mweb_url
              }&redirect_url=${encodeURIComponent(redirect_url)}`;
            } else {
              this.$toast(
                this.$t("locale.mobile.wallet.t24") + H5WxResult.data
                  ? H5WxResult.data.msg
                  : null
              );
            }
          }
        }
      } else if (this.payType == 3) {
        let params = {
          questionGroupId: this.question_id,
          userId: this.user_info.id,
          price: this.turnString(__price__),
          ip: returnCitySN.cip,
          type: 4,
          payType: 3
        };
        let result = await generateOrder(params);
        if (result && result.data && result.data.code == 200) {
          const { orderNo } = result.data.data;
          this.orderNo = orderNo;
          if (window.hasOwnProperty("flutter_inappwebview")) {
            console.log(
              "=====================支付宝App支付====================="
            );
            let aliPayResult = await getCourseBuyAlipayAppPay({
              orderNo: this.currentOrderNo
            });
            if (
              aliPayResult &&
              aliPayResult.data &&
              aliPayResult.data.code == 200
            ) {
              let arg = JSON.stringify({
                type: "alipay",
                data: aliPayResult.data.data
              });
              // this.appAliPayInfo = JSON.stringify(aliPayResult.data.data);
              window.flutter_inappwebview.callHandler("Pay", arg).then(res => {
                console.log("支付宝支付成功！");
                console.log(res);
              });
            } else {
              this.$toast(
                "支付失败" + aliPayResult.data ? aliPayResult.data.msg : null
              );
            }
          } else {
            console.log("=====================支付宝支付=====================");
            let resultPay = await getCourseBuyToH5Alipay(this.orderNo);
            if (resultPay && resultPay.data && resultPay.data.code == 200) {
              window.location.href = resultPay.data.data;
            } else {
              this.$toast(
                this.$t("locale.mobile.wallet.t24") + resultPay.data
                  ? resultPay.data.msg
                  : null
              );
            }
          }
        } else if (result && result.data && result.data.code == 420) {
          this.$toast(this.$t("locale.mobile.order.t14"));
        } else if (result && result.data && result.data.code == 1001) {
          this.$toast("课程购买人数达到上限！");
        } else {
          this.$toast(this.$t("locale.mobile.order.t15"));
        }
      } else {
        this.$toast("请选择您的支付方式");
      }
      return;
    }
  },
  deactivated() {
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  destroyed() {
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  activated(){
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }
      if (this.$route.query.isSuccess == 1) {
        // 支付成功--获取题库id
        this.pay_success = true;
        this.paySuccess();
      }else{
        this.getQueationDetail();
        this.wxBrowserPay()
      }
    }
  },
  created() {
    // if (process.client) {
    //   if (!this.token && Object.keys(this.user_info).length == 0) {
    //     this.$router.replace("/m/login");
    //     return;
    //   }
    //   if (this.$route.query.isSuccess == 1) {
    //     // 支付成功--获取题库id
    //     this.pay_success = true;
    //     this.paySuccess();
    //   }else{
    //     this.getQueationDetail();
    //     this.wxBrowserPay()
    //   }
    // }
  }
};
</script>

<style lang="scss" scoped>
.mobile-question-purchase {
  position: relative;
  width: 7.2rem;
  padding: .2rem .2rem 1rem;
  min-height: 100vh;
  background-color: #f5f5f5;
  .purchase-detail {
    width: 100%;
    .purchase-detail-content {
      width: 100%;
      display: flex;
      justify-content: space-between;
      // border-bottom: 1px solid #ddd;
      background: #ffffff;
      padding: 0.2rem;
      border-radius: 0.1rem;
      .purchase-detail-left {
        width: 2.52rem;
        height: 1.73rem;
        .purchase-detail-left-cover {
          display: block;
          width: 100%;
          height: 100%;
        }
      }
      .purchase-detail-right {
        width: 3.6rem;
        .purchase-detail-name {
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          max-height: 0.7rem;
          font-size: 0.32rem;
          color: #010101;
          line-height: 0.35rem;
        }
        .purchase-detail-coursename {
          margin: 0.15rem 0;
          color: #969799;
          font-size: 0.28rem;
        }
        .purchase-detail-price {
          font-size: 0.28rem;
          color: #ff8a8a;
          .old_price {
            color: #969799;
            text-decoration: line-through;
          }
        }
      }
    }
    .purchase-detail-pay_list {
      padding: 0 0.192rem;
      background: #ffffff;
      margin-top: 0.3rem;
      border-radius: 0.1rem;
      .pay_item {
        width: 100%;
        height: 1rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 0.3rem;
        box-sizing: border-box;
        padding: 0 0.2rem;
        // border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        &.border-bottom {
          border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }
        .pay_item_left {
          display: flex;
          align-items: center;
          img {
            width: 0.48rem;
            height: 0.48rem;
            display: block;
            margin-right: 0.14rem;
          }
        }
      }
    }
    .bottom-area {
      width: 7.2rem;
      height: 1rem;
      position: fixed;
      bottom: 0;
      left: 0;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      border-top: 1px solid rgba(0, 0, 0, 0.1);
      background-color: #ffffff;
      .bottom-area-price {
        font-size: 0.28rem;
        span {
          color: var(--theme-color);
        }
      }
      .bottom-area-pay-btn {
        width: 2rem;
        height: 0.8rem;
        border-radius: 0.4rem;
        background: var(--theme-color);
        color: #fff;
        text-align: center;
        font-size: 0.3rem;
        line-height: 0.8rem;
        margin: 0 0.2rem;
      }
    }
  }
}
</style>
